package com.gaoyi.crm.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.gaoyi.crm.R;
import com.gaoyi.crm.adapter.ImageAdapter;
import com.gaoyi.crm.callback.IPhotoCallBack;
import com.gaoyi.crm.callback.IView;
import com.gaoyi.crm.callback.OnEndClickListener;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.constant.BundleKeyName;
import com.gaoyi.crm.constant.RequestCode;
import com.gaoyi.crm.control.dialog.ComboDialogUtils;
import com.gaoyi.crm.control.dialog.ConfirmDialog;
import com.gaoyi.crm.control.dialog.LoadingDialogUtils;
import com.gaoyi.crm.control.popup.MyListPopupWindow;
import com.gaoyi.crm.databinding.FragmentNewPromotionBinding;
import com.gaoyi.crm.db.dto.ShortDto;
import com.gaoyi.crm.db.entity.ItemNoStore;
import com.gaoyi.crm.db.entity.Pmn;
import com.gaoyi.crm.db.entity.PmnAttach;
import com.gaoyi.crm.fragment.base.BaseFragment;
import com.gaoyi.crm.util.DensityUtil;
import com.gaoyi.crm.util.PermissionUtils;
import com.gaoyi.crm.util.PhotoUtils;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.util.Utils;
import com.gaoyi.crm.vm.NewPromotionViewModel;
import com.gs.zxinglibrary.zxing.activity.CaptureActivity;
import com.gs.zxinglibrary.zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NewPromotionFragment extends BaseFragment<FragmentNewPromotionBinding, NewPromotionViewModel> implements IView {

    private ActivityResultLauncher<Intent> mCameraResult, mFileResult, mScanResult;
    private ImageAdapter mImageAdapter;
    private MyListPopupWindow mPopupWindowCus;
    private ConfirmDialog mDialog;
    private List<ShortDto> mCustomersList, mCurList;
    private MyBroadcast mBroadcast;
    private String mId;
    private int mFilePos;
    private boolean mIsRecordEdit;
    // 从scannedListFragment返回时传递过来的数据，防止在scan时点击back按钮清空全部数据了
    private List<ItemNoStore> mLastItemNoStores;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_new_promotion;
    }

    @Override
    protected void initView() {
        Bundle bundle = getArguments();
        if (bundle != null && bundle.getBoolean(BundleKeyName.IS_EDIT, false)) {
            mIsRecordEdit = true;
            mId = bundle.getString(BundleKeyName.ID);
            mBinding.viewDescription.setVisibility(View.VISIBLE);
            mBinding.btnSave.setVisibility(View.VISIBLE);
            mBinding.tvBack.setVisibility(View.GONE);
            mBinding.llBtn.setVisibility(View.GONE);
        } else {
            mIsRecordEdit = false;
            mBinding.viewRemark.setEditTextHeight(DensityUtil.dp2px(170));
            mBinding.btnSave.setVisibility(View.GONE);
            mBinding.tvBack.setVisibility(View.VISIBLE);
            mBinding.llBtn.setVisibility(View.VISIBLE);
        }
        mBinding.viewCusName.setOnEndClickListener(new MyOnEndClickListener());
        mBinding.viewCusName.addTextChangedListener(new MyTextWatcher());
        mImageAdapter = new ImageAdapter(mContext);
        mImageAdapter.setOnItemLongClickListener((v, position) -> deletePhoto(position));
        mBinding.rvImage.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.rvImage.setAdapter(mImageAdapter);
        mBinding.rvImage.setItemAnimator(null);
        mBinding.editScroll.setOnScrollChangeListener((View.OnScrollChangeListener) (view, i, i1, i2, i3) -> scrolling());
        MyOnClickListener onClickListener = new MyOnClickListener();
        mBinding.tvBack.setOnClickListener(onClickListener);
        mBinding.btnUpload.setOnClickListener(onClickListener);
        mBinding.btnSave.setOnClickListener(onClickListener);
        mBinding.btnClear.setOnClickListener(onClickListener);
        mBinding.btnScan.setOnClickListener(onClickListener);
        mCameraResult = registerForActivityResult(RequestCode.REQUEST_CAMERA);
        mFileResult = registerForActivityResult(RequestCode.REQUEST_FILE);
        mScanResult = registerForActivityResult(RequestCode.REQUEST_SCAN);
        initPopupWindow();
        initBroadcast();
        // 监听返回到此页面时携带的数据
        getParentFragmentManager().setFragmentResultListener(BundleKeyName.RESULT, mContext, (requestKey, result) -> {
            if (requestKey.equals(BundleKeyName.RESULT)) {
                mLastItemNoStores = result.getParcelableArrayList(BundleKeyName.RESULT);
                mViewModel.getScanList().clear();
                if (mLastItemNoStores != null && !mLastItemNoStores.isEmpty()) {
                    mViewModel.getScanList().addAll(mLastItemNoStores);
                }
            }
        });
    }

    private void initBroadcast() {
        mBroadcast = new MyBroadcast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(CaptureActivity.MY_ACTION);
        mContext.registerReceiver(mBroadcast, filter);
    }

    @Override
    protected void initLiveData() {
        mCurList = new ArrayList<>();
        mCustomersList = new ArrayList<>();
        mViewModel.getCusList().observe(mOwner, shortDtos -> {
            mCustomersList.addAll(shortDtos);
            mCurList.addAll(shortDtos);
            mPopupWindowCus.setData(shortDtos);
        });
        mViewModel.getPhotoList().observe(mOwner, imageBeans -> mImageAdapter.submitList(imageBeans));
        mViewModel.getIsExist().observe(mOwner, isExist -> {
            if (isExist == null) {
                return;
            }
            if (isExist) {
                ToastUtil.showToast(R.string.pmn_exist);
                return;
            }
            Utils.scan(mContext, mScanResult, 0);
        });
        mViewModel.getResultCode().observe(mOwner, integer -> {
            if (integer == ApiStatus.FAIL) { // 查询失败，返回Record页
                mContext.onBackPressed();
            }
        });
        mViewModel.getUpdateCode().observe(mOwner, integer -> {
            if (integer == ApiStatus.SUCCESS) {
                ToastUtil.showToast(R.string.save_successful);
            }
        });
    }

    /**
     * 滑动时取消PopupWindow的显示
     */
    private void scrolling() {
        Utils.dismissPopupWindow(mPopupWindowCus);
    }

    /**
     * 删除上传的图片
     */
    private void deletePhoto(int position) {
        mFilePos = position;
        String photo = mImageAdapter.getCurrentList().get(mFilePos).getAttach();
        if (mDialog == null) {
            mDialog = ConfirmDialog.newInstance(mContext, getString(R.string.delete_photo, photo.substring(photo.lastIndexOf("/") + 1)),
                    () -> mViewModel.removePhoto(mFilePos));
            mDialog.show(getChildFragmentManager());
        } else {
            mDialog.setTitle(getString(R.string.delete_photo, photo.substring(photo.lastIndexOf("/") + 1)));
            mDialog.show();
        }
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    private class MyOnEndClickListener implements OnEndClickListener {

        @Override
        public void onEndClickListener() {
            mCurList.clear();
            mCurList.addAll(mCustomersList);
            mPopupWindowCus.setData(mCustomersList);
            showCusPopupWindow();
        }
    }

    private class MyTextWatcher implements TextWatcher {

        String text;

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            text = charSequence.toString().trim();
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String content = editable.toString().trim();
            if (content.equals(text)) {
                return;
            }
            if (content.isEmpty()) {
                if (mPopupWindowCus.isShowing()) {
                    mPopupWindowCus.dismiss();
                }
            } else {
                // 模糊查询
                mCurList.clear();
                Pattern pattern = Pattern.compile(Pattern.quote(content));
                for (ShortDto dto : mCustomersList) {
                    Matcher matcher = pattern.matcher(dto.getName());
                    if (matcher.find()) {
                        mCurList.add(dto);
                    }
                }
                mPopupWindowCus.setData(mCurList);
                if (!mPopupWindowCus.isShowing()) {
                    mPopupWindowCus.show();
                }
            }
        }
    }

    private class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.btn_upload) {
                upload();
            } else if (id == R.id.btn_scan) {
                scan();
            } else if (id == R.id.btn_clear) {
                clear();
            } else if (id == R.id.tv_back) {
                mContext.onBackPressed();
            } else if (id == R.id.btn_save) {
                save();
            }
        }
    }

    /**
     * 保存修改的Record
     */
    private void save() {
        Pmn bean = mViewModel.getPmnEdit().getValue();
        if (bean == null) {
            bean = new Pmn();
        }
        setPmnData(bean);
        bean.setModifyAt(new Date());
        bean.setModifyId(Utils.getUserId());
        bean.setSyncedStatus(ApiStatus.NO_UPLOAD);
        bean.setDescription(mBinding.viewDescription.getText());
        mViewModel.updatePmn(bean);
    }

    private void scan() {
        View currentFocus = mContext.getCurrentFocus();
        if (currentFocus != null) {
            mContext.getCurrentFocus().clearFocus(); // 清除焦点，使EditInputView更新数据
        }
        String code = mViewModel.getProId().getValue();
        if (code == null || code.trim().isEmpty()) {
            ToastUtil.showToast(R.string.pro_no_not_empty);
            return;
        }
        String proEnName = mViewModel.getProEnName().getValue();
        if (proEnName == null || proEnName.trim().isEmpty()) {
            ToastUtil.showToast(R.string.pro_name_not_empty);
            return;
        }
        // 判断code是否已存在
        mViewModel.codeIsExist(code);
    }

    private void showCusPopupWindow() {
        if (mPopupWindowCus.isShowing()) {
            mPopupWindowCus.dismiss();
        } else {
            mPopupWindowCus.show();
        }
    }

    private void initPopupWindow() {
        mPopupWindowCus = new MyListPopupWindow(mContext);
        mPopupWindowCus.setHeight(DensityUtil.dp2px(200));
        mPopupWindowCus.setAnchorView(mBinding.viewCusName.getEditView());
        mPopupWindowCus.setOnItemClickListener((adapterView, view, i, l) -> {
            ShortDto customer = mCurList.get(i);
            String name = customer.getName();
            mBinding.viewCusName.setText(name);
            mBinding.viewCusName.setTag(customer.getId());
            mBinding.viewCusName.setSelection(name.length());
            mPopupWindowCus.dismiss();
        });
    }

    /**
     * 清空数据
     */
    private void clear() {
        mViewModel.clearPhoto();
        mViewModel.getScanList().clear();
        mBinding.viewProNo.setText("");
        mBinding.viewProEnName.setText("");
        mBinding.viewCusName.setText("");
        mBinding.viewRemark.setText("");
    }

    @Override
    protected void initData() {
        // 获取customer列表
        mViewModel.getCustomers();
        if (mIsRecordEdit) { // 编辑record，获取Pmn
            mViewModel.getPmn(mId);
        }
    }

    /**
     * 上传文件
     */
    private void upload() {
        ComboDialogUtils.showComboPicDialog(mContext, new IPhotoCallBack() {
            @Override
            public void camera() {
                if (PermissionUtils.addPermission(mContext, new String[]{Manifest.permission.CAMERA
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE}, mPermissionsResult)) {
                    PhotoUtils.getInstance().toCamera(mContext, mCameraResult);
                }
            }

            @Override
            public void file() {
                if (PermissionUtils.addPermission(mContext, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, mPermissionsResult)) {
                    PhotoUtils.getInstance().toFile(mFileResult);
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        Utils.onPauseDialog(mDialog);
    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {
        if (PermissionUtils.requestPermissionResult(result, Manifest.permission.CAMERA)
                && PermissionUtils.requestPermissionResult(result, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            PhotoUtils.getInstance().toCamera(mContext, mCameraResult);
        } else if (PermissionUtils.requestPermissionResult(result, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            PhotoUtils.getInstance().toFile(mFileResult);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {
        if (result.getResultCode() == 0) {
            return;
        }
        switch (requestCode) {
            case RequestCode.REQUEST_CAMERA:
                addFile(PhotoUtils.getInstance().getCameraResult(mContext));
                break;
            case RequestCode.REQUEST_FILE:
                addFile(PhotoUtils.getInstance().getFileResult(mContext, result));
                break;
            case RequestCode.REQUEST_SCAN:
                scanResult(result);
                break;
        }
    }

    /**
     * 添加文件
     *
     * @param fileName 文件名
     */
    private void addFile(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return;
        }
        PmnAttach pmnAttach = new PmnAttach();
        pmnAttach.setAttach(fileName);
        mViewModel.addPhoto(pmnAttach);
    }

    /**
     * 处理扫描返回
     *
     * @param result 扫描结果
     */
    private void scanResult(ActivityResult result) {
        Intent data = result.getData();
        if (result.getResultCode() == 0 || data == null) {
            return;
        }
        Bundle extras = data.getExtras();
        if (extras == null) {
            return;
        }
        if (extras.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FINISH) == CodeUtils.RESULT_BACK) {
            mViewModel.getScanList().clear();
            if (mLastItemNoStores != null && !mLastItemNoStores.isEmpty()) {
                mViewModel.getScanList().addAll(mLastItemNoStores);
            }
            return;
        }
        Pmn bean = new Pmn();
        setPmnData(bean);
        bean.setItemNos(mViewModel.getScanList());
        Bundle bundle = new Bundle();
        bundle.putParcelable(BundleKeyName.RESULT, bean);
        mController.navigate(R.id.action_newPromotionFragment_to_scannedListFragment, bundle);
        mViewModel.setIsExist(null);
    }

    private void setPmnData(Pmn bean) {
        bean.setCode(mBinding.viewProNo.getText());
        bean.setEnName(mBinding.viewProEnName.getText());
        bean.setCustomerEnName(mBinding.viewCusName.getText());
        bean.setCustomerCnName(mBinding.viewCusName.getText());
        Object custId = mBinding.viewCusName.getTag();
        bean.setCustomerId(custId == null ? null : custId.toString());
        bean.setRemark(mBinding.viewRemark.getText());
        bean.setImages(mViewModel.getPhotoList().getValue());
    }

    /**
     * 接受扫描二维码结果的广播
     **/
    private class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action) && action.equals(CaptureActivity.MY_ACTION)) {
                String result = intent.getStringExtra(CodeUtils.RESULT_STRING);
                if (!TextUtils.isEmpty(result)) {
                    mViewModel.getItemNo(result);
                }
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (mPopupWindowCus != null && mPopupWindowCus.isShowing()) {
                mPopupWindowCus.dismiss();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBroadcast != null) {
            mContext.unregisterReceiver(mBroadcast);
        }
        if (mPopupWindowCus != null && mPopupWindowCus.isShowing()) {
            mPopupWindowCus.dismiss();
        }
    }
}